package com.xmhmyh.generalframework.common.utils;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @Author: 于丁
 * redis 分布式锁
 * @DateTime: 2020/9/1 1:49 下午
 */
@Component
public class RedissonLockUtils {
    @Autowired
    private RedissonClient redissonClient;

    // redis默认时间 10s
    public static final Long DEFAULT_LOCK_TIME = 10L;
    // redis获取锁的默认等待时间 5s
    public static final Long LOCK_WAIT_TIME = 5L;

    public void lock(String lockName, Long time, TimeUnit timeUnit) {
        RLock rLock = redissonClient.getLock(lockName);
        rLock.lock(time, timeUnit);
    }

    public void lock(String lockName, Long time) {
        RLock rLock = redissonClient.getLock(lockName);
        rLock.lock(time, TimeUnit.SECONDS);
    }

    public void lock(String lockName) {
        RLock rLock = redissonClient.getLock(lockName);
        rLock.lock(DEFAULT_LOCK_TIME, TimeUnit.SECONDS);
    }

    public boolean tryLock(String lockName) {
        RLock rLock = redissonClient.getLock(lockName);
        Boolean res = null;
        try {
            return rLock.tryLock(LOCK_WAIT_TIME, DEFAULT_LOCK_TIME, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean tryLock(String lockName, Long time, TimeUnit timeUnit) {
        RLock rLock = redissonClient.getLock(lockName);
        Boolean res = null;
        try {
            return rLock.tryLock(LOCK_WAIT_TIME, time, timeUnit);
        } catch (InterruptedException e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean tryLock(String lockName, Long time) {
        RLock rLock = redissonClient.getLock(lockName);
        Boolean res = null;
        try {
            return rLock.tryLock(LOCK_WAIT_TIME, time, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
            return false;
        }
    }

    public void unLock(String lockName) {
        RLock rLock = redissonClient.getLock(lockName);
        rLock.unlock();
    }
}
